package cn.bug.greenflag.controller;

import cn.bug.greenflag.pojo.dto.FaceSearchResDto;
import cn.bug.greenflag.pojo.dto.ProcessInfo;
import cn.bug.greenflag.pojo.vo.AdminFaceLoginVO;
import cn.bug.greenflag.service.IAdminService;
import cn.bug.greenflag.web.JsonResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @author chenlang
 * @version v1.0
 * @Data 2022/9/12  21:25
 */
@RestController
@Api("1. 登录模块")
@Slf4j
public class LoginController {


    @Autowired
    private IAdminService adminService;


    @PostMapping("/faceAdd")
    @ApiOperation("面部绑定")
    @ApiOperationSupport(order = 10)
    public JsonResult<Void> faceAdd(@RequestParam("file") String file ) {

        if(file == null){
            throw new RuntimeException("上传的图片为空");
        }
        byte[] decode = Base64.decode(base64Process(file));
        ImageInfo imageInfo = ImageFactory.getRGBData(decode);

        // TODO: 根据sercurity存放的数据获取到id
        Long id = 1L;

        adminService.faceAdd(imageInfo,id);
        return JsonResult.ok();
    }




    @PostMapping("/faceLogin")
    @ApiOperation("脸部识别登录")
    @ApiOperationSupport(order = 20)
    public JsonResult<?> faceLogin(String file) throws Exception{

        byte[] decode = Base64.decode(base64Process(file));
        BufferedImage bufImage = ImageIO.read(new ByteArrayInputStream(decode));
        ImageInfo imageInfo = ImageFactory.bufferedImage2ImageInfo(bufImage);


        //人脸特征获取
        byte[] bytes = adminService.extractFaceFeature(imageInfo);
        if (bytes == null) {
            //return Results.newFailedResult(ErrorCodeEnum.NO_FACE_DETECTED);
             throw new RuntimeException();
        }
        //人脸比对，获取比对结果
        List<AdminFaceLoginVO> userFaceInfoList = adminService.compareFaceFeature(bytes);

        if (CollectionUtil.isNotEmpty(userFaceInfoList)) {
            AdminFaceLoginVO AdminFaceLoginVO = userFaceInfoList.get(0);
            FaceSearchResDto faceSearchResDto = new FaceSearchResDto();
            BeanUtil.copyProperties(AdminFaceLoginVO, faceSearchResDto);
            List<ProcessInfo> processInfoList = adminService.process(imageInfo);
            if (CollectionUtil.isNotEmpty(processInfoList)) {
                //人脸检测
                List<FaceInfo> faceInfoList = adminService.detectFaces(imageInfo);
                int left = faceInfoList.get(0).getRect().getLeft();
                int top = faceInfoList.get(0).getRect().getTop();
                int width = faceInfoList.get(0).getRect().getRight() - left;
                int height = faceInfoList.get(0).getRect().getBottom() - top;

                Graphics2D graphics2D = bufImage.createGraphics();
                graphics2D.setColor(Color.RED);//红色
                BasicStroke stroke = new BasicStroke(5f);
                graphics2D.setStroke(stroke);
                graphics2D.drawRect(left, top, width, height);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(bufImage, "png", outputStream);
                byte[] bytes1 = outputStream.toByteArray();
                faceSearchResDto.setImage("data:image/png;base64," + Base64Utils.encodeToString(bytes1));
                faceSearchResDto.setAge(processInfoList.get(0).getAge());
                faceSearchResDto.setGender(processInfoList.get(0).getGender().equals(1) ? "女" : "男");
            }
            //TODO 人脸匹配成功: 返回的数据为: faceSearchResDto: 此处应该返回token
            return JsonResult.ok(faceSearchResDto);
        }
        // 面部匹配不成功
        return JsonResult.fail(404,"面部匹配不成功");

    }
    private String base64Process(String base64Str) {
        if (!StringUtils.isEmpty(base64Str)) {
            String photoBase64 = base64Str.substring(0, 30).toLowerCase();
            int indexOf = photoBase64.indexOf("base64,");
            if (indexOf > 0) {
                base64Str = base64Str.substring(indexOf + 7);
            }

            return base64Str;
        } else {
            return "";
        }
    }
}
